package com.solr.self.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.common.SolrDocumentList;

/**
 * 
 * <solr默认查询实现类>
 * <功能详细描述>
 * 
 * @author  huanglizhi
 * @version  [版本号, 2012-7-10]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class DefaultSolrjQuery implements SolrjQuery { 
    
//    private org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass()); 

	/**
	 * <获取查询结果，返回SolrDocument记录的集合>
	 * <功能详细描述>
	 * 
	 * @param word
	 * @param sbpo
	 * @return DataGrid<List<Map<String,Object>>>
	 */
	public DataGrid<SolrDocumentList> querySolrResult(String word, SolrSearchBasePO sbpo) {
		
		DataGrid<SolrDocumentList> dataGrid = new DataGrid<SolrDocumentList>();
		// 建立solrQuery对象
		SolrQuery query = new SolrQuery();
		// 设置组装好的查询语句
		query.setQuery(word);
		// 从多少条开始
		query.setStart(sbpo.getOffset());
		// 每页显示多少行
		query.setRows(sbpo.getLimit());
		// 设置特殊属性，包含要返回的字段、排序、高亮
		SolrjCommonUtil.SetSpecialProperties(query, sbpo);
		CommonsHttpSolrServer httpSolrServer = SolrServer.getServer();
//		CommonsHttpSolrServer httpSolrServer = SolrServer.getInstance().getServer();
		try {
			System.out.println("query : "+query);
			QueryResponse rsp = httpSolrServer.query(query);
			
			//得到所有的documents（数据）
			SolrDocumentList docs = rsp.getResults();
			
			// 如果启用了高亮，则将高亮后的数据填充doc
			if(sbpo.getIs_hl()){
				SolrjCommonUtil.SetHighlightData(rsp, docs, sbpo);
			}
			dataGrid.setData(docs);
			System.out.println("count : "+(int)docs.getNumFound());
			dataGrid.setTotalElements((int)docs.getNumFound());
		} catch (SolrServerException e) {
			e.printStackTrace();
		}
		return dataGrid;
	} 
	
	/**
	 * <获取查询结果，并将SolrDocument格式转化为Map格式输出>
	 * <功能详细描述>
	 * 
	 * @param word
	 * @param sbpo
	 * @return DataGrid<List<Map<String,Object>>>
	 */
	public DataGrid<List<Map<String,Object>>> querySolrResultForMap(String word, SolrSearchBasePO sbpo) {
		
		// 获取查询结果SolrDocumentList
		DataGrid<SolrDocumentList> jsonDataGrid = querySolrResult(word, sbpo);
		// 将SolrDocument格式数据转化为Map格式输出
		List<Map<String,Object>> dataList = SolrjCommonUtil.SolrDocumentConvertToMap(jsonDataGrid.getData());
		DataGrid<List<Map<String,Object>>> listDataGrid = new DataGrid<List<Map<String,Object>>>();
		listDataGrid.setData(dataList);
		listDataGrid.setTotalElements(jsonDataGrid.getTotalElements());
		return listDataGrid;
	} 
	
	/**
	 * <获取查询结果，并将json格式转化为bean对象输出>
	 * <功能详细描述>
	 * 
	 * @param word
	 * @param sbpo
	 * @param clazz
	 * @return DataGrid<List<T>>
	 */
	public <T> DataGrid<List<T>> querySolrResultForBO(String word, SolrSearchBasePO sbpo ,Class<T> clazz) {
		
		DataGrid<List<T>> dataGrid = new DataGrid<List<T>>();
		// 建立solrQuery对象
		SolrQuery query = new SolrQuery();
		// 设置组装好的查询语句
		query.setQuery(word);
		// 从多少条开始
		query.setStart(sbpo.getOffset());
		// 每页显示多少行
		query.setRows(sbpo.getLimit());
		
		// 设置特殊属性，包含要返回的字段、排序、高亮
		SolrjCommonUtil.SetSpecialProperties(query, sbpo);
		CommonsHttpSolrServer httpSolrServer = SolrServer.getServer();
//		CommonsHttpSolrServer httpSolrServer = SolrServer.getInstance().getServer();
		try {
			System.out.println("query : "+query);
			QueryResponse rsp = httpSolrServer.query(query);
			List<T> beanList = new ArrayList<T>();
			// 根据是否要高亮字段来执行操作，如果不需要高亮，则直接调用solrj中得getBeans得到bean记录集合
			if(sbpo.getIs_hl()){
				//得到所有的documents（数据）
				SolrDocumentList docs = rsp.getResults();
				// 如果启用了高亮，则将高亮后的数据填充doc
				SolrjCommonUtil.SetHighlightData(rsp, docs, sbpo);
				beanList = httpSolrServer.getBinder().getBeans(clazz,docs); 
				System.out.println("count : "+(int)docs.getNumFound());
				dataGrid.setTotalElements((int)docs.getNumFound());
			}else {
				beanList = rsp.getBeans(clazz);
				System.out.println("count : "+beanList.size());
				dataGrid.setTotalElements(beanList.size());
			}
			dataGrid.setData(beanList);
		} catch (SolrServerException e) {
			e.printStackTrace();
		}
		return dataGrid;
	}
	
	/**
	 * <获取分组统计结果>
	 * <功能详细描述>
	 * 
	 * @param word
	 * @param sbpo
	 * @return Map<String, Map<String, Long>>
	 */
	public Map<String, Map<String, Long>> querySolrResultForFacet(String word, SolrSearchBasePO sbpo) {
		
		Map<String, Map<String, Long>> facetCountMap = new HashMap<String, Map<String, Long>>();
		Map<String, Long> countMap = new HashMap<String, Long>();
		// 建立solrQuery对象
		SolrQuery query = new SolrQuery();
		// 设置组装好的查询语句
		query.setQuery(word);
		
		// 设置特殊属性，包含要返回的字段、排序、高亮
		SolrjCommonUtil.SetFacet(query, sbpo);
		CommonsHttpSolrServer httpSolrServer = SolrServer.getServer();
//		CommonsHttpSolrServer httpSolrServer = SolrServer.getInstance().getServer();
		try {
			System.out.println("query : "+query);
			QueryResponse rsp = httpSolrServer.query(query);
			List<FacetField> facets = rsp.getFacetFields();
			if (null != facets) {
				for (FacetField facet : facets) {
					String facetFiled = facet.getName();
					List<Count> counts = facet.getValues();
					for (Count count : counts) {
						countMap.put(count.getName(), count.getCount());
					}
					facetCountMap.put(facetFiled, countMap);
				}
			}
		} catch (SolrServerException e) {
			e.printStackTrace();
		}
		return facetCountMap;
	}
	
} 